<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Userfarmrecord as UserfarmrecordMdl;
use app\admin\model\Userfarm;
use app\admin\model\Image;

use think\Db;
use think\Exception;
use think\Request;

class Userfarmrecord extends BaseController
{

    /**
     * 列表
     */
    public function getList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $where = [
            'userId' => $userId
        ];

        // 筛选
        if(!empty($param->farmId)){
            $where['farmId'] = $param->farmId;
        }

        $model = new UserfarmrecordMdl();
        $fields = '*';
        $order = 'createDate DESC';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }

        foreach ($result as $item) {
            $item['farmName'] = Userfarm::where('id', $item['farmId'])->value('name');
            $item['workTime'] = date('Y-m-d H:i:s');
            $item['farmingProject'] = explode(',', $item['farmingProject']);
            $item['formulas'] = json_decode($item['formulas'], true);
            // 图片
            $item['imgList'] = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->order('sorting ASC')->select();
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new UserfarmrecordMdl();
        $field = '*';
        $item = $model->where($where)->field($field)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关数据');
        }

        $item['farmName'] = Userfarm::where('id', $item['farmId'])->value('name');
        $item['workTime'] = date('Y-m-d H:i:s');
        $item['farmingProject'] = explode(',', $item['farmingProject']);
        $item['formulas'] = json_decode($item['formulas'], true);
        // 图片
        $item['imgList'] = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->order('sorting ASC')->select();

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 保存
     */
    public function save()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->farmId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '农场ID(farmId) 不能为空');
        }
        if (empty($param->workTime)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '劳作时间(workTime) 不能为空');
        }
        if (empty($param->temperature)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '温度(temperature) 不能为空');
        }
        if (empty($param->weather)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '天气(weather) 不能为空');
        }
        if (empty($param->phenological)) {
            //return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '物候期(phenological) 不能为空');
        }
        if (empty($param->farmingProject)) {
            //return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '农事项目(farmingProject) 不能为空');
        }
        if (empty($param->remarks)) {
            //return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '备注(remarks) 不能为空');
        }

        $userId = $param->userId;

        Db::startTrans();
        try {
            $data = (array)$param;
            $data['workTime'] = strtotime($data['workTime']);
            $data['farmingProject'] = implode(',', $data['farmingProject']);
            /*
            // 药剂/肥料 用法，即配方 Demo
            $formulas = [
                [
                    'formula' => [
                        [
                            //'fertilizer' => '', // 肥料
                            //'medicament' => '', // 药剂
                            'name' => '', // 肥料/药剂
                            'amount' => '', // 用量
                            'unit' => '', // 单位
                            //'dilutionFactor' => '', // 稀释倍数
                            'water' => '', // 兑水多少，单位L
                        ],
                        [
                            'name' => '', // 肥料/药剂
                            'amount' => '', // 用量
                            'unit' => '', // 单位
                            'water' => '', // 兑水多少，单位L
                        ]
                    ],
                    'isAddwater' => '1', // 是否兑水，1：兑水 2：不兑水
                    'area' => '' // 使用面积
                ],
            ];
            */
            // 药剂/肥料 用法，即配方
            $formulas = json_encode($param->formulas);
            $data['formulas'] = $formulas;

            $model = new UserfarmrecordMdl();
            if (!empty($param->id)) {
                $id = $param->id;
                $data['updateDate'] = time();
                $data['userId'] = $userId;

                $result = $model->allowField(true)->save($data, ['id' => $id]);
            } else {
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();

                $result = $model->save($data);
            }

            if($result !== false){
                // 图片
                $res = '';
                if(isset($param->imgUrls) && $param->imgUrls) {
                    $imgUrls = (array) $param->imgUrls;
                    foreach($imgUrls as $key => $imgUrl){
                        $res = Image::where(['imgUrl' => $imgUrl])->update(['relatedId' => $data['id'], 'relatedTable' => 'userfarmrecord', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '保存图片失败');
                }
                Db::commit();
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '保存失败', $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '保存失败', $e->getMessage());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 删除
     */
    public function delete()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new UserfarmrecordMdl();
        $result = $model->where($where)->delete();
        if ($result === false) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
        }

        // Query执行后的操作
        $model->_after_delete($param->id);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

}